package com.blb.zy_community.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.blb.zy_community.entity.ResponseResult;
import com.blb.zy_community.entity.SysPost;
import com.blb.zy_community.entity.SysRole;
import com.blb.zy_community.entity.ZyCommunity;
import com.blb.zy_community.service.ISysRoleDeptService;
import com.blb.zy_community.service.ISysRoleMenuService;
import com.blb.zy_community.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import javax.management.relation.Role;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色信息表 前端控制器
 * </p>
 *
 * @author 二组
 * @since 2023-06-18
 */
@RestController
@CrossOrigin
public class SysRoleController {
    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysRoleMenuService sysRoleMenuService;

    @Autowired
    private ISysRoleDeptService sysRoleDeptService;

    /**
     * 角色分页
     * @param current
     * @param size
     * @param roleName
     * @param roleKey
     * @param roleStatus
     * @param timeDate
     * @return
     */
    @GetMapping("/role-page")
    public ResponseResult<Page<SysRole>> getRolePage(@RequestParam(required = false,defaultValue = "1") Long current,
                                                     @RequestParam(required = false,defaultValue = "5") Long size,
                                                     @RequestParam(required = false,defaultValue = "") String roleName,
                                                     @RequestParam(required = false,defaultValue = "") String roleKey,
                                                     @RequestParam(required = false,defaultValue = "") String roleStatus,
                                                     @RequestParam(required = false,defaultValue = "") String[] timeDate){
        String startTime = "";
        String endTime ="";
        if (timeDate!=null){
            boolean isEmpty=false;
            for (int i = 0; i < timeDate.length; i++) {
                if (timeDate[i].equals("null")){
                    isEmpty=true;
                    break;
                }
            }
            if (!isEmpty){
                startTime= timeDate[0];
                endTime= timeDate[1];
            }
        }
        Page<SysRole> page = sysRoleService.selectRolePage(new Page<>(current, size),roleName,roleKey,roleStatus,startTime,endTime);
        return ResponseResult.ok(page);
    }



//    @DeleteMapping("/role/{id}")
//    public ResponseResult<String> deleteRole(@PathVariable Long id){
//        sysRoleService.removeById(id);
//        return ResponseResult.ok(id);
//    }

    /**
     * 修改角色删除状态
     * @param roleId
     * @return
     */
    @PutMapping("/role/{roleId}")
    public ResponseResult<String> updateDElFlag(@PathVariable Long roleId){
        sysRoleService.updateDelFlagId(roleId);
        return ResponseResult.ok(roleId);
    }

    /**
     * 批量删除
     * @param roleIds
     * @return
     */
    @DeleteMapping("/roles/{roleIds}")
    public ResponseResult<String> deleteRoles(@PathVariable Long[] roleIds){
        sysRoleService.deleteRoles(roleIds);
        return ResponseResult.ok(roleIds);
    }

    /**
     * 添加角色
     * @param param
     * @return
     */
    @PostMapping("/role")
        public ResponseResult<String> addRole(@RequestBody Map<String,Object> param){
        try {
            Object role = param.get("role");
            Object menuId = param.get("menuId");
            SysRole sysRole = JSON.parseObject(JSON.toJSONString(role), new TypeReference<SysRole>() {
            });
            List<Long> menuIds = JSON.parseObject(JSON.toJSONString(menuId), new TypeReference<List<Long>>() {
            });
            sysRole.setDelFlag("0");
            sysRole.setCreateTime(LocalDateTime.now());
            sysRoleService.addRoleAndMenu(sysRole, menuIds);
            return ResponseResult.ok(param);
        } catch (Exception e) {
            return ResponseResult.error(500L,"error");
        }
    }

    /**
     * 添加数据权限
     */
    @PostMapping("roleDept")
    public ResponseResult<String> addDept(@RequestBody Map<String,Object> param){
        Object role = param.get("role");
        Object depts = param.get("depts");
        SysRole sysRole = JSON.parseObject(JSON.toJSONString(role), new TypeReference<SysRole>() {
        });
        List<Long> deptIds = JSON.parseObject(JSON.toJSONString(depts), new TypeReference<List<Long>>() {
        });
        sysRoleService.addRoleAndDept(sysRole,deptIds);
        return ResponseResult.ok(param);
    }

    /**
     * 修改角色
     * @return
     */
    @PutMapping("/role")
    public ResponseResult<String> updateRole(@RequestBody Map<String,Object> param){
        Object role = param.get("role");
        Object menuId = param.get("menuId");
        SysRole sysRole = JSON.parseObject(JSON.toJSONString(role), new TypeReference<SysRole>() {
        });
        List<Long> menuIds = JSON.parseObject(JSON.toJSONString(menuId), new TypeReference<List<Long>>() {
        });
        sysRole.setUpdateTime(LocalDateTime.now());
        sysRoleService.updateRoleAndMenu(sysRole,menuIds);
        return ResponseResult.ok(sysRole);
    }

    /**
     * 修改角色状态
     */
    @PutMapping("/role-status/{roleId}")
    public ResponseResult<String> updateStatus(@PathVariable Long roleId){
        SysRole sysRole = sysRoleService.getOne(new QueryWrapper<SysRole>().eq("role_id", roleId));
        String status = "0";
        if ("0".equals(sysRole.getStatus())){
            status = "1";
        }
        sysRoleService.updateStatus(Long.valueOf(status),roleId);
        return ResponseResult.ok(status);
    }

    /**
     * 根据角色id查询当前的菜单权限
     */
    @RequestMapping("/role-ids/{roleId}")
    public ResponseResult<List<Long>> getMenuByRole(@PathVariable Long roleId){
        List<Long> menusIds = sysRoleMenuService.selectMenuByRoleId(roleId);
        return ResponseResult.ok(menusIds);
    }
    /**
     * 根据角色id查询当前的部门权限
     */
    @RequestMapping("/role-dept/{roleId}")
    public ResponseResult<List<Long>> getDeptByRole(@PathVariable Long roleId){
        List<Long> deptByRoleId = sysRoleDeptService.selectDeptByRoleId(roleId);
        return ResponseResult.ok(deptByRoleId);
    }

    /**
     * 根据id查询单个信息
     */
    @RequestMapping("role/{id}")
    public ResponseResult<String> getRoleOne(@PathVariable Long id ){
        SysRole sysRole = sysRoleService.getOne(new QueryWrapper<SysRole>().eq("role_id", id));
        return ResponseResult.ok(sysRole);
    }

    /**
     * 获取角色表集合
     * @return
     */
    @GetMapping("/roleName")
    public ResponseResult<String> getRoleName(){
        List<SysRole> list = sysRoleService.list();
        return ResponseResult.ok(list);
    }

}
